//
//  XiaoXIViewController.m
//  ZhiBoYuan
//
//  Created by coder_di on 2018/4/27.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "XiaoXIViewController.h"
#import "WBChatModel.h"
#import "WBChatCell.h"

@interface XiaoXIViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray *dataArray;

@property (nonatomic, assign)int page;

@end

@implementation XiaoXIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"消息详情";
    
    [self addTableView];
    
    _dataArray = [NSMutableArray array];
    
    _page = 1;
    
    [self loadData];
    
    [self.tableView registerClass:[WBChatCell class] forCellReuseIdentifier:@"WBChatCell"];
    
}

-(void)loadData{
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"page":[NSString stringWithFormat:@"%d",_page],
                       @"page_count": @"10"
                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Ucenter&a=newsList",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        
        NSDictionary *dic = responseObject;
        
        if ([dic[@"status"] intValue] == 200) {
            
            NSArray *array = dic[@"data"][@"news_list"];
            
            if (array.count > 0) {
                int i =0;
                
                for (NSDictionary *dicc in dic[@"data"][@"news_list"]) {
                    
                    WBChatModel *model = [WBChatModel new];
                    [model setValuesForKeysWithDictionary:dicc];
                    model.msgFrom = 1;
                    
                    if (_page == 1) {
                        if (i == 0) {
                            UserinfoModel *model = [ZYUserManager userInfo];
                            model.unreadMessageId = [dic[@"data"][@"news_list"][0] valueForKey:@"id"];
                            [ZYUserManager saveUserInfo:model];
                           
                        }
                        [_dataArray addObject:model];
                    }else{
                        [_dataArray insertObject:model atIndex:0];
                    }
                     i++;
                }
                
                
                if (_page == 1) {
                    _dataArray=(NSMutableArray *)[[_dataArray reverseObjectEnumerator] allObjects];
                }
                
                if (_page == 1) {
                    [self.tableView reloadData];
                }else{
                    
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:array.count inSection:0];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
                    });
                }
            }
        }else{
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:1.5f];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}


-(void)addTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT ) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    _tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 下拉刷新
    _tableView.mj_header= header;
    
    [header setTitle:@"加载更多" forState:MJRefreshStateIdle];
    [header setTitle:@"正在加载" forState:MJRefreshStatePulling];
    [header setTitle:@"加载中..." forState:MJRefreshStateRefreshing];
    
    [self.view addSubview:_tableView];
}

-(void)loadNewData{
    
    self.page = _page + 1;
    
    [self loadData];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [_tableView.mj_header endRefreshing];
        
    });
}

#pragma mark - Navigation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    
    return 0;
    
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifity = @"BanJiTableViewCell";
    WBChatCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[WBChatCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifity];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    cell.model = _dataArray[indexPath.row];
    
    if (_page == 1) {
        if (indexPath.row == _dataArray.count -1) {
            [self tableViewScrollToBottom];
            
        }
    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //计算文字高度需和自定义cell内容尺寸同步
    WBChatModel *msgModel = [[WBChatModel alloc] init];
    msgModel = self.dataArray[indexPath.row];
    CGSize labelSize = [msgModel.content boundingRectWithSize: CGSizeMake(ScreenWidth-160 * KscreenWidth, MAXFLOAT * KscreenHeight)
                                                      options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine
                                                   attributes: @{NSFontAttributeName:[UIFont systemFontOfSize:15 * KscreenHeight]}
                                                      context: nil].size;
    
    if (indexPath.row == self.dataArray.count - 1) {
        return labelSize.height + 170 * KscreenHeight;
    }else{
        return labelSize.height + 100  * KscreenHeight;
        
    }
    
}

- (void)tableViewScrollToBottom {
    
    if (self.dataArray.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
